from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.views.generic import date_based
from django.views.generic import list_detail
from django.template.loader import select_template

from pennypress.apps.categories.models import Section

def section_archive_day(request, section, year, month, day, queryset, date_field, **kwargs):
    section = get_object_or_404(Section, section_category__slug=section)
    queryset = queryset.filter(section=section)
    template = select_template(['categories/%ssection_archive_day.html' % section.category.slug ,'categories/section_archive_day.html']).name
    return date_based.archive_day(request,
        queryset=queryset,
        year=year, 
        month=month, 
        day=day,
        date_field=date_field, 
        template_name = template, 
        extra_context={'section':section})

def section_archive_month(request, section, year, month, queryset, date_field, **kwargs):
    section = get_object_or_404(Section, category__slug=section)
    queryset = queryset.filter(section=section)
    template = select_template(['categories/%ssection_archive_month.html' % section.category.slug ,'categories/section_archive_month.html']).name
    return date_based.archive_month(request,
        queryset=queryset, 
        year=year, 
        month=month, 
        date_field=date_field,
        template_name = template, 
        extra_context={'section':section})

def section_archive_year(request, section, year, queryset, date_field, **kwargs):
    section = get_object_or_404(Section, category__slug=section)
    queryset = queryset.filter(section=section)
    template = select_template(['categories/%ssection_archive_year.html' % section.category.slug ,'categories/section_archive_year.html']).name
    return date_based.archive_year(request,
        queryset=queryset,  
        year=year,
        date_field=date_field,
        template_name = template, 
        extra_context={'section':section})

def section_detail(request, section, queryset, paginate_by, **kwargs):
    section = get_object_or_404(Section, category__slug=section)
    queryset = queryset.filter(section=section)
    template = select_template(['categories/%ssection_list.html' % section.category.slug ,'categories/section_list.html']).name
    return list_detail.object_list(request,
        queryset=queryset, 
        template_name = template, 
        paginate_by=paginate_by, 
        extra_context={'section':section})

def section_latest(request, section, queryset):
    section = get_object_or_404(Section, category__slug=section)
    try:
        obj = queryset.filter(section=section)[0]
    except:
        return Http404
    return HttpResponseRedirect(obj.get_absolute_url())